/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package main

import (
	"flag"
	"fmt"

	"gitee.com/WisdomClassroom/cli/action"
	"gitee.com/WisdomClassroom/cli/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

func main() {
	core.PublicFlag(BuildTag, BuildGo, BuildTime)
	flag.IntVar(&glb.AccountID, "root-account", 0, "root account id")
	flag.StringVar(&glb.Name, "root-name", "", "root name")
	flag.StringVar(&glb.Password, "root-password", "", "root password")
	flag.Parse()

	if core.FlagHelp {
		flag.Usage()
		return
	}
	if core.FlagVersion {
		core.PublicVersion()
		return
	}
	if !core.FlagUseSqlite && !core.FlagUsePG {
		flag.Usage()
		return
	}

	glb.Logger = core.NewLogger(core.FlagLogLevel)

	config := &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: logger.New(
			glb.Logger,
			logger.Config{
				LogLevel: core.GetGormLogLevel(),
				Colorful: false,
			},
		),
	}
	var err error
	if core.FlagUseSqlite {
		glb.DB, err = gorm.Open(sqlite.Open(core.FlagSqliteDB), config)
	} else {
		glb.DB, err = gorm.Open(postgres.Open(models.GetPgSQLConf()), config)
	}
	if err != nil {
		glb.Logger.Error(err.Error())
	}

	if accountID := action.CreateRoot(); accountID == 0 {
		glb.Logger.Info("Create Root User failed")
	} else {
		glb.Logger.Info(fmt.Sprintf("Create Root User successfully: %d", accountID))
	}
}
